<template>
  <view class="pay_box">
    <!-- <view class="time" v-if="countdownStore.showM == 0 && countdownStore.showS == 0">订单已超时</view> -->
    <view class="time" >
      <!-- 支付剩余时间 -->
      <!-- <uni-countdown
        color="#888"
        :show-day="false"
        :show-hour="false"
        :minute="countdownStore.showM"
        :second="countdownStore.showS"
        @timeup="timeup1()"
      >
      </uni-countdown> -->

      支付剩余时间：{{ rocallTime }}


    </view>
    <view class="price">￥{{ orderAmount }}</view>
    <view class="shop">xxx餐馆 - {{ orderNumber }}</view>
    <view class="wechat">
      <image class="pay" src="../../static/icon/pay.png" />
      微信支付
      <image class="choose" src="../../static/icon/choose.png" />
    </view>
    <view class="bottom">
      <button class="comfirm_btn" type="primary" :plain="true" @click="toSuccess()">确认支付</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {getOrderAPI, payOrderAPI, cancelOrderAPI} from '@/api/order'
import {onLoad, onShow, onUnload} from '@dcloudio/uni-app'
// import {useCountdownStore} from '@/memberPages/stores/modules/countdown'
import {Ref, ref} from 'vue'
import md5 from 'js-md5'; // 局部引入
// const countdownStore = useCountdownStore()

const orderId = ref(0) // 订单id
const orderNumber = ref('') // 订单号
const orderAmount = ref(0) // 订单金额
const orderTime = ref<Date>() // 订单时间

const countdownRef = ref(null)

onLoad(async (options: any) => {
// 获取当前本地时间
  console.log("onLoad");
  nowDate();


  console.log('orderTime什么东西？', options)
  orderId.value = options.orderId
  orderNumber.value = options.orderNumber
  orderAmount.value = options.orderAmount
  orderTime.value = options.orderTime.replace(' ', 'T')
})

// 支付成功
const toSuccess =  () => {
  // // 若订单已超时，跳转到订单已取消页面
  // if (countdownStore.showM == -1 && countdownStore.showS == -1) {
  //   uni.redirectTo({
  //     url: '/pages/orderDetail/orderDetail?orderId=' + orderId.value,
  //   })
  //   return
  // }
  // console.log('支付成功')
  // // 支付后修改订单状态
  // const payDTO = {
  //   orderNumber: orderNumber.value,
  //   payMethod: 1, // 本平台默认微信支付
  // }
  // const res = await payOrderAPI(payDTO)



  // // 关闭定时器
  // if (countdownStore.timer !== undefined) {
  //   clearInterval(countdownStore.timer)
  //   countdownStore.timer = undefined
  // }
  // uni.redirectTo({
  //   url:
  //     '/pages/submit/success?orderId=' +
  //     orderId.value +
  //     '&orderNumber=' +
  //     orderNumber.value +
  //     '&orderAmount=' +
  //     orderAmount.value +
  //     '&orderTime=' +
  //     orderTime.value,
  // })


        //设置模拟弹窗
        // uni.showModal({
        //     title: '此时唤起微信支付，输入微信密码【当前为模拟付款】',
        //     content: '',
        //     showCancel: true,
        // 	cancelText:'取消',
        //   confirmText:'确认支付',
        //     success: async({ confirm, cancel }) => {
        //       console.log(confirm);
        //       if (confirm) {
        //         //真

        //       // // 支付后修改订单状态
        //         const payDTO = {
        //           orderNumber: orderNumber.value,
        //           payMethod: 1, // 本平台默认微信支付
        //         }
        //         const res = await payOrderAPI(payDTO)

        //         if(res.code === 0){
        //             //返回主页
        //             uni.showToast({
        //                 title: '支付成功！',
        //                 icon: 'success',
        //                 mask: true
        //             })
        //             //
        //             setTimeout(() => {
        //               uni.switchTab({ url: "/pages/my/my" })
        //             }, 500);
                    
        //         }else{
        //           //失败
        //           uni.showToast({
        //                 title: '支付失败！！',
        //                 icon: 'error',
        //                 mask: true
        //             })
        //             setTimeout(() => {
        //                //退回my页面
        //           uni.switchTab({ url: "/pages/my/my" })
        //             }, 500);
               

        //         }
        //       } else {
        //       }
        //     }
        //   })   
          
        toPay()

}

// 倒计时
// const timeup = () => {
//   console.log('------------ 执行了一次倒计时timeup ---------------')
//   // setInterval间歇调用，每隔一秒调用一次
//   let timeupSecond = ref(20)
//   // 如果 timer 已经存在，先清除它
//   if (countdownStore.timer !== undefined) {
//     clearInterval(countdownStore.timer)
//   }
//   countdownStore.timer = setInterval(() => {
//     console.log('什么timer？', countdownStore.timer)
//     console.log('看看是不是一秒执行一次', orderTime.value)
//     // 订单下单时间
//     let buy_time = new Date(orderTime.value as Date).getTime()
//     // 计算剩余时间
//     // 测试20秒就够，正式15分钟
//     // let time = buy_time + 20 * 1000 - new Date().getTime()
//     // 最终代码是15分钟，测试时我才没那个功夫时间等！
//     let time = buy_time + 15 * 60 * 1000 - new Date().getTime()
//     console.log('time', time)
//     if (time > 0 && countdownStore.timer !== undefined) {
//       // 计算剩余的分钟
//       var m = (time / 1000 / 60) % 60
//       console.log('m', m)
//       // 计算剩余的秒数
//       var s = (time / 1000) % 60
//       console.log('s', s)
//       timeupSecond.value = time / 1000
//       console.log('timeupSecond小于0？', timeupSecond.value)
//       countdownStore.showM = Math.floor(m)
//       countdownStore.showS = Math.floor(s)
//       // showTime.value = minutes.value + ':' + seconds.value
//     } else {
//       console.log('订单已超时！')
//       clearInterval(countdownStore.timer) // 停止计时器
//       // 再重置pinia中的倒计时的分秒初始值
//       countdownStore.showM = -1
//       countdownStore.showS = -1
//       // uni.showToast({
//       //   title: '时间到',
//       // })
//       // 取消订单
//       cancelOrder()
//     }
//   }, 1000)
// }

// 超时要取消订单
const cancelOrder = async () => {
  await cancelOrderAPI(orderId.value)
  // uni.redirectTo({
  //   url: '/pages/orderDetail/orderDetail?orderId=' + orderId.value,
  // })
}


// --------------------------------------------------------------------------



const toPay = ()=>{

console.log("toPay");



// 1.小程序下单 ，获取 prepay_id





// 2.获取prepay_id 后 ，准备参数，调起支付


const appid =  "wxd930ea5d5a258f4f"

const mch_id=  "10000100"

const device_info= "1000"

const body= "test"

const nonce_str= "ibuaiVcKdpRxkhJA"

const stringA="appid="+appid+"&body="+body+"&device_info="+ device_info+"&mch_id="+mch_id +"&nonce_str="+nonce_str +"";

const key = ""
// MD5签名方式：

const stringSignTemp=stringA+"&key="+key+"" //注：key为商户平台设置的密钥key

const sign=md5(stringSignTemp).toUpperCase() //注：MD5签名方式

console.log("sign::",sign);




// prepay_id


  // 仅作为示例，非真实参数信息。
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: String(Date.now()),
      nonceStr: 'A1B2C3D4E5',
      package: 'prepay_id=wx20180101abcdefg',
      signType: 'MD5',
      paySign: sign,
      success: function (res) {
        console.log('success:' + JSON.stringify(res));
      },
      fail: function (err) {
        console.log('fail:' + JSON.stringify(err));
      }
    });

}




// 系统时间
const nowDateText = ref("")

// 倒计时,默认未结束
const timeout = ref(true)

const rocallTime = ref("")

const times11: Ref<number | undefined>  = ref(undefined); // 定时器引用


onShow(()=>{
  console.log("onShow");
  initData()
})

onUnload(()=>{
  console.log("onUnload");
  clearTimeout(times11.value)
})


// 获取当前时间
  const nowDate = ()=>{
    console.log("获取当前时间:");
  
    var date = new Date();  
        var year = date.getFullYear();  
        var month = String(date.getMonth() + 1).padStart(2, '0');  
        var day = String(date.getDate()).padStart(2, '0');  
        var hours = String(date.getHours()).padStart(2, '0');  
        var minutes = String(date.getMinutes()).padStart(2, '0');  
          
        var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;  
          nowDateText.value = formattedTime
        console.log(formattedTime); // 输出类似于：2024-04-19 11:57
  }

  const initData = ()=>{
      // 2024-04-18 21:43
      runTimeBack(nowDateText.value)
    }


const timeup1 = ()=>{
  console.log("timeup1!!");
  
}




// 订单倒计时
    // 2024-04-18 21:43
    const runTimeBack = (time:string)=> {
      console.log(time,1)
      var end = Date.parse(time.replace(/-/g, "/"));

      var now = Date.parse(new Date()+"");
      var m15 = 15 * 60 * 1000;
      var msec = m15 - (now - end);
      console.log();
      if (msec < 0) {
        timeout.value = true;
        clearTimeout(times11.value);
        //cancel(orderId.value+""); //超时的时候取消订单
        cancelOrder()
      } else {
        var min = msec / 1000 / 60 % 60;
        var sec = msec / 1000 % 60;
        if (min < 10) {
         var min1 = '0' + Math.floor(min);
        } else {
         var min1 = String( Math.floor(min));
        }
        if (sec < 10) {
          var sec1 = '0' + sec;
        } else {
          var sec1 = String(sec);
        }
        rocallTime.value = min1 + ':' + sec1;
        console.log("rocallTime.value::",rocallTime.value);
        
        // var that = this;
        if (min >= 0 && sec >= 0) {
          if (min === 0 && sec === 0) {
            timeout.value = true;
            clearTimeout(times11.value);
           // cancel(String(orderId)); //超时的时候取消订单
            cancelOrder()
            return;
          }
          times11.value = setTimeout(function () {
            runTimeBack(time);
            console.log("runTimeBack()");
          }, 1000);
        }
      }
    }




    // 取消订单
    // const cancel =async(id:string)=>{
    //       const res = await cancelApi(id)
    //       if(res.code === 1){
    //         uni.showToast({
    //               title: '订单已取消！',
    //               icon: 'success',
    //               mask: true
    //           })

    //           uni.switchTab({
    //             url:'/pages/index/index',
    //           })
            
    //       }
    //     }




</script>

<style lang="less" scoped>
.pay_box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #333;
  .time {
    display: flex;
    margin-top: 100rpx;
    color: #888;
    font-size: 28rpx;
  }
  .price {
    font-size: 80rpx;
    font-weight: bold;
    margin-top: 20rpx;
  }
  .shop {
    display: flex;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #888;
  }
  .wechat {
    display: flex;
    width: 90%;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #fff;
    border-radius: 10rpx;
    margin: 100rpx 20rpx;
    position: relative;
    .pay {
      width: 40rpx;
      height: 40rpx;
      padding: 20rpx;
    }
    .choose {
      position: absolute;
      width: 40rpx;
      height: 40rpx;
      top: 20rpx;
      right: 20rpx;
    }
  }
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .comfirm_btn {
    position: absolute;
    bottom:55rpx;
    width: 600rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    background: #00aaff;
    border: none;
    color: #fff;
    font-size: 30rpx;
    text-align: center;
  }
}
</style>

<style>
page {
  background-color: #f8f8f8;
}
</style>
